from flask import Flask, render_template, request, jsonify, redirect, url_for
from flask_cors import CORS
from controller.upload_controller import upload_bp
from service.base_service.task_service import TaskService
from service.process_service import ProcessService

app = Flask(__name__)
app.register_blueprint(upload_bp)
CORS(app)


@app.route('/get_all_tasks')
def get_all_tasks():
    # 使用 jsonify 返回 JSON 格式的数据
    # return render_template('show_tasks.html', tasks=TaskService().get_all_tasks_auto())
    return jsonify(TaskService().get_all_tasks_auto())


@app.route('/update_task', methods=['POST'])
def update_task():
    task_service = TaskService()
    task_id = request.form.get('id')
    # 收集所有需要更新的字段
    updates = {}
    for key in request.form:
        if key.startswith('task_'):
            updates[key[len('task_'):]] = request.form[key]

    # 更新任务
    success = task_service.update_task_by_id(task_id, **updates)

    if success:
        # 如果更新成功，则重定向回到显示任务的页面
        return redirect(url_for('get_tasks'))
    else:
        # 如果更新失败，则返回错误页面或者显示错误消息
        return "Failed to update the task."


@app.route('/process/<int:task_id>', methods=['POST', 'GET'])
def process_task(task_id):
    # 获取固定参数 task_id
    # 在URL中已经获取到了 task_id，不需要从请求体中获取

    # 获取其他动态参数
    # dynamic_params = request.form.to_dict()
    dynamic_params = request.args.to_dict()

    # 处理任务
    result = ProcessService().process_task_with_params(dispatch_code="self", task_id=task_id,
                                                       dynamic_params=dynamic_params)

    # 返回处理结果
    return jsonify({"status": "success", "message": "Task processed successfully.", "result": result})


if __name__ == '__main__':
    app.run(debug=True)
